<template>
	<scroll-view scroll-y="true" @scrolltolower="handleReachBottom" style="height: 100%;">
		<view class="early-warning-page">
			<!-- 搜索栏 -->
			<view class="search-bar">
				<view class="search-input-wrap">
					<text class="search-icon">🔍</text>
					<input class="search-input" placeholder="请输入所属人搜索" v-model="keyword" @input="handleInput" />
					<text class="clear-icon" v-if="keyword" @click="clearSearch">×</text>
				</view>
				<button class="search-btn" @click="toSearch">搜索</button>
			</view>

			<!-- 预警列表 -->
			<view class="warning-list" v-if="waringData.length">
				<view class="warning-item" v-for="(item, index) in waringData" :key="index">
					<!-- 预警头部 -->
					<view class="warning-header">
						<view class="warning-tag" :class="getLevelClass(item.level)">
							{{ getLevelText(item.level) }}
						</view>
						<view class="warning-id">编号: {{ item.id }}</view>
					</view>

					<!-- 预警内容 -->
					<view class="warning-content">
						<view class="info-row">
							<view class="info-label">水权量:</view>
							<view class="info-value">{{ item.waterRight }}</view>
						</view>
						<view class="info-row">
							<view class="info-label">所属人:</view>
							<view class="info-value">{{ item.ownerName }}</view>
						</view>
						<view class="info-row">
							<view class="info-label">预警时间:</view>
							<view class="info-value">{{ formatTime(item.exceedDate) }}</view>
						</view>
						<view class="info-row">
							<view class="info-label">设备编号:</view>
							<view class="info-value">{{ item.deviceId || '暂无' }}</view>
						</view>
						<view class="info-row">
							<view class="info-label">项目地址:</view>
							<view class="info-value multi-line">{{ item.projectNames?.join(',') || '暂无' }}</view>
						</view>
						<view class="info-row">
							<view class="info-label">处理内容:</view>
							<view class="info-value multi-line">{{ item.processContent }}</view>
						</view>
					</view>

					<!-- 操作按钮 -->
					<view class="warning-actions">
						<button class="action-btn detail-btn" @click="viewDeviceDetail(item)">
							查看设备详情
						</button>
						<button class="action-btn handle-btn" @click="handleWarning(item)" :disabled="item.processed"
							:class="{ disabled: item.status == 1 }">
							{{ item.status == 1 ? '已处理' : '处理' }}
						</button>
					</view>
				</view>
			</view>

			<!-- 加载状态 -->
			<view class="loading-state" v-if="isLoading && waringData.length == 0">
				<view class="loading-spinner"></view>
				<text class="loading-text">加载中...</text>
			</view>

			<!-- 空状态 -->
			<view class="empty-state" v-if="!isLoading && waringData.length == 0">
				<image class="empty-img" src="/static/images/empty-warning.png" mode="widthFix"></image>
				<text class="empty-text">暂无预警信息</text>
				<button class="refresh-btn" @click="toSearch">刷新</button>
			</view>

			<!-- 加载更多 -->
			<view class="load-more" v-if="hasMore && waringData.length > 0 && !isLoading">
				<view class="loading-spinner small"></view>
				<text class="load-more-text">加载更多</text>
			</view>
			<view class="no-more" v-if="!hasMore && waringData.length > 0 && !isLoading">
				已显示全部信息
			</view>
		</view>
	</scroll-view>

	<!-- 处理弹窗 -->
	<view class="process-modal-mask" v-if="showProcessModal" @click="closeModal"></view>
	<view class="process-modal" v-if="showProcessModal">
		<view class="modal-header">
			<text class="modal-title">处理预警</text>
			<text class="modal-close" @click="closeModal">×</text>
		</view>
		<view class="modal-body">
			<view class="form-item">
				<text class="form-label">处理结果</text>
				<view class="radio-group">
					<view class="radio-item" v-for="(opt, i) in processOptions" :key="i">
						<view class="radio" :class="{ checked: processResult == opt.value }"
							@click="processResult = opt.value"></view>
						<text class="radio-label">{{ opt.label }}</text>
					</view>
				</view>
			</view>
			<view class="form-item">
				<text class="form-label">处理说明</text>
				<textarea class="process-textarea" v-model="processContent" placeholder="请输入处理情况..."
					maxlength="200"></textarea>
				<text class="text-count">{{ processContent.length }}/200</text>
			</view>
		</view>
		<view class="modal-footer">
			<button class="modal-btn cancel-btn" @click="closeModal">取消</button>
			<button class="modal-btn confirm-btn" @click="submitProcess" :loading="isSubmitting">
				提交处理
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { AlarmInfoPageApi,ProcessAlarmApi } from "@/axios/pageApi/waning";

// 数据状态
const waringData = ref([]);
const keyword = ref('');
const current = ref(1);
const size = ref(10);
const isLoading = ref(false);
const hasMore = ref(true);
const isSubmitting = ref(false);
const totalCount = ref(0)
// 处理弹窗相关
const showProcessModal = ref(false);
const currentProcessItem = ref(null);
const processResult = ref(1);
const processContent = ref('');

// 处理选项
const processOptions = [
	{ label: '已处理', value: 1 },
	{ label: '暂不处理', value: 0 },
];

// 初始化
onMounted(() => {
	getAlarmwarninInfo();
});

// 获取预警数据
async function getAlarmwarninInfo(e) {
	if (isLoading.value) return;
	if(e && totalCount.value && (waringData.value.length >= totalCount.value)) return
	isLoading.value = true;

	try {
		const res = await AlarmInfoPageApi({
			current: current.value,
			ownerName: keyword.value
		});
		
		console.log(res, '==rew');
		totalCount.value = Number(res.data.total)
		if (res.code == 0) {
			const newData = res.data.records.map(item => ({
				...item,
				processed: item.status == 2,
				level: item.level || 1
			}));

			waringData.value =  [...waringData.value, ...newData];
			if(waringData.value.length >= totalCount.value){
				hasMore.value = false
				isLoading.value = false;
			}
			console.log(isLoading.value,waringData.value.length,Number(res.data.total), hasMore.value,'===waringData');
		}
	} catch (e) {
		console.error('获取预警数据失败:', e);
	} finally {
		isLoading.value = false;
	}
}

// 加载更多
const handleReachBottom = () => {
	current.value++;
	getAlarmwarninInfo('加载');
};

// 搜索相关
const handleInput = (e) => {
	keyword.value = e.detail.value;
};

const clearSearch = () => {
	keyword.value = '';
};

const toSearch = () => {
	current.value = 1;
	waringData.value = [];
	getAlarmwarninInfo();
};

// 预警级别处理
const getLevelText = (level) => {
	switch (level) {
		case 1: return '一般预警';
		case 2: return '重要预警';
		case 3: return '紧急预警';
		default: return '预警';
	}
};

const getLevelClass = (level) => {
	switch (level) {
		case 1: return 'level-normal';
		case 2: return 'level-important';
		case 3: return 'level-emergency';
		default: return '';
	}
};

// 时间格式化
const formatTime = (timeStr) => {
	if (!timeStr) return '';
	const date = new Date(timeStr);
	return `${date.getFullYear()}-${padZero(date.getMonth() + 1)}-${padZero(date.getDate())} ${padZero(date.getHours())}:${padZero(date.getMinutes())}:${padZero(date.getSeconds())}`;
};

const padZero = (num) => num.toString().padStart(2, '0');

// 操作方法
const viewDeviceDetail = (item) => {

	uni.navigateTo({
		url: `/pages/detailsPage/detailsPage?name=${item.deviceId}`,
	});
};

const handleWarning = (item) => {
	currentProcessItem.value = item;
	processResult.value = 1;
	processContent.value = '';
	showProcessModal.value = true;
};

const closeModal = () => {
	showProcessModal.value = false;
};

const submitProcess = async () => {
	console.log(processResult.value,processContent.value);
	if (!processContent.value.trim()) {
		return uni.showToast({ title: '请输入处理说明', icon: 'none' });
	}
	
	isSubmitting.value = true;
	try {
		const obj = {
			dealdesc: processContent.value,
			status: processResult.value,
			id: currentProcessItem.value.id
		}
		// 调用处理接口逻辑
		const res = await ProcessAlarmApi(obj);
		if (res.code == 0) {
		uni.showToast({ title: '处理成功', icon: 'success' });
		// 更新本地数据状态
		const index = waringData.value.findIndex(item => item.id == currentProcessItem.value.id);
		if (index > -1) {
			waringData.value[index].processed = true;
		}
		showProcessModal.value = false;
		}
	} catch (e) {
		console.error('处理失败:', e);
		uni.showToast({ title: '处理失败', icon: 'none' });
	} finally {
		isSubmitting.value = false;
	}
};
</script>

<style scoped>
/* 基础样式 */
.early-warning-page {
	padding: 16rpx;
	background-color: #f5f7fa;
	min-height: 100vh;
}

/* 搜索栏 */
.search-bar {
	position: fixed;
	display: flex;
	z-index: 999;
	width: 95%;
	align-items: center;
	gap: 12rpx;
	margin-bottom: 20rpx;
}

.search-input-wrap {
	flex: 1;
	display: flex;
	align-items: center;
	background: #fff;
	border-radius: 8rpx;
	padding: 0 20rpx;
	height: 72rpx;
	border: 1px solid #eee;
}

.search-icon {
	color: #999;
	font-size: 30rpx;
	margin-right: 10rpx;
}

.search-input {
	flex: 1;
	height: 100%;
	font-size: 28rpx;
	color: #333;
}

.clear-icon {
	color: #ccc;
	font-size: 24rpx;
	width: 36rpx;
	height: 36rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border-radius: 50%;
	background: #f5f5f5;
}

.search-btn {
	width: 120rpx;
	height: 72rpx;
	line-height: 72rpx;
	background: #4e94e1;
	color: #fff;
	font-size: 28rpx;
	border-radius: 8rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	border: none;
}

/* 预警列表 */
.warning-list {
	z-index: 1;

	display: flex;
	flex-direction: column;
	gap: 16rpx;
	margin-top: 45px;
}

.warning-item {
	background: #fff;
	border-radius: 12rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

/* 预警头部 */
.warning-header {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
}

.warning-tag {
	padding: 4rpx 16rpx;
	border-radius: 20rpx;
	font-size: 24rpx;
	color: #fff;
	font-weight: 500;
}

.level-normal {
	background-color: #52c41a;
}

.level-important {
	background-color: #faad14;
}

.level-emergency {
	background-color: #ff4d4f;
}

.warning-id {
	font-size: 24rpx;
	color: #666;
	margin-left: 16rpx;
}

/* 预警内容 */
.warning-content {
	margin-bottom: 24rpx;
}

.info-row {
	display: flex;
	margin-bottom: 16rpx;
}

.info-row:last-child {
	margin-bottom: 0;
}

.info-label {
	width: 140rpx;
	font-size: 26rpx;
	color: #666;
	flex-shrink: 0;
}

.info-value {
	flex: 1;
	font-size: 26rpx;
	color: #333;
	word-break: break-all;
}

.multi-line {
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

/* 操作按钮 */
.warning-actions {
	display: flex;
	gap: 16rpx;
	margin-top: 20rpx;
}

.action-btn {
	flex: 1;
	height: 70rpx;
	line-height: 70rpx;
	font-size: 26rpx;
	border-radius: 8rpx;
	border: none;
	display: flex;
	align-items: center;
	justify-content: center;
}

.detail-btn {
	background-color: #e6f7ff;
	color: #1890ff;
}

.handle-btn {
	background-color: #fff2e8;
	color: #fa8c16;
}

.handle-btn.disabled {
	background-color: #f5f5f5;
	color: #ccc;
}

/* 状态提示 */
.loading-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
	padding: 100rpx 0;
}

.loading-spinner {
	width: 40rpx;
	height: 40rpx;
	border: 4rpx solid #eee;
	border-top-color: #4e94e1;
	border-radius: 50%;
	animation: spin 1s linear infinite;
}

.loading-spinner.small {
	width: 30rpx;
	height: 30rpx;
}

.loading-text {
	font-size: 28rpx;
	color: #999;
	margin-top: 16rpx;
}

.empty-state {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 100rpx 0;
	color: #999;
}

.empty-img {
	width: 200rpx;
	height: 200rpx;
	margin-bottom: 24rpx;
	opacity: 0.7;
}

.empty-text {
	font-size: 28rpx;
	margin-bottom: 30rpx;
}

.refresh-btn {
	font-size: 26rpx;
	color: #4e94e1;
	background: transparent;
	border: 1px solid #4e94e1;
	padding: 8rpx 30rpx;
	border-radius: 6rpx;
}

.load-more {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 30rpx 0;
	color: #999;
	font-size: 26rpx;
}

.load-more-text {
	margin-left: 12rpx;
}

.no-more {
	text-align: center;
	padding: 30rpx 0;
	color: #999;
	font-size: 26rpx;
}

/* 处理弹窗 */
.process-modal-mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 998;
}

.process-modal {
	position: fixed;
	left: 50%;
	bottom: 0;
	width: 100%;
	max-width: 600rpx;
	background-color: #fff;
	border-radius: 20rpx 20rpx 0 0;
	transform: translateX(-50%);
	z-index: 999;
	padding: 24rpx;
	box-sizing: border-box;
}

.modal-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 24rpx;
}

.modal-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.modal-close {
	font-size: 36rpx;
	color: #999;
}

.modal-body {
	margin-bottom: 24rpx;
}

.form-item {
	margin-bottom: 28rpx;
}

.form-label {
	display: block;
	font-size: 28rpx;
	color: #333;
	margin-bottom: 12rpx;
}

.radio-group {
	display: flex;
	gap: 30rpx;
}

.radio-item {
	display: flex;
	align-items: center;
}

.radio {
	width: 28rpx;
	height: 28rpx;
	border-radius: 50%;
	border: 2rpx solid #ccc;
	margin-right: 10rpx;
	position: relative;
}

.radio.checked {
	border-color: #4e94e1;
}

.radio.checked::after {
	content: '';
	position: absolute;
	top: 50%;
	left: 50%;
	width: 16rpx;
	height: 16rpx;
	background-color: #4e94e1;
	border-radius: 50%;
	transform: translate(-50%, -50%);
}

.radio-label {
	font-size: 26rpx;
	color: #333;
}

.process-textarea {
	width: 100%;
	min-height: 160rpx;
	padding: 16rpx;
	border: 1px solid #eee;
	border-radius: 8rpx;
	font-size: 26rpx;
	line-height: 1.6;
	resize: none;
	box-sizing: border-box;
}

.process-textarea:focus {
	outline: none;
	border-color: #4e94e1;
}

.text-count {
	display: block;
	text-align: right;
	font-size: 24rpx;
	color: #999;
	margin-top: 8rpx;
}

.modal-footer {
	display: flex;
	gap: 16rpx;
	margin-top: 16rpx;
}

.modal-btn {
	flex: 1;
	height: 80rpx;
	line-height: 80rpx;
	font-size: 28rpx;
	border-radius: 8rpx;
	border: none;
}

.cancel-btn {
	background-color: #f5f5f5;
	color: #666;
}

.confirm-btn {
	background-color: #4e94e1;
	color: #fff;
}

/* 动画 */
@keyframes spin {
	0% {
		transform: rotate(0deg);
	}

	100% {
		transform: rotate(360deg);
	}
}

/* 按钮禁用样式 */
button:disabled {
	opacity: 0.7;
}
</style>